//#ifndef MAC_OS
#include "stdafx.h"
#include <stdio.h>
#include <string.h>
//#endif
#include "CSprite.h"

#ifdef MAC_OS
#include <stdarg.h>
#elif defined(ANDROID_OS)
#include <stdarg.h>
#include "../../../_android/jni/jni_Util.h"
#endif

float*	CSprite::_uv = new float[4];
UNICHAR* CSprite::_uni_buffer = new UNICHAR[256];
char* CSprite::_ansi_buffer = new char[256];
static const char * fileNames [6]= { "chicken.png", 
						"duck.png", 
						"geese.png", 
						"egg.png", 
						"shit.png", 
						"basket.png"};
	
CSprite::CSprite()
{
	_texture_image_data = NULL;
	_texture_image_w = new INT32[NUM_RESOURCE_TEXTURE];
	_texture_image_h = new INT32[NUM_RESOURCE_TEXTURE];
	_type = -1;
}

CSprite::~CSprite()
{	
	Unload();
}

void CSprite::Load(bool is_create_texture, bool linear_texture, INT8 palette_mask)
{
	for(int i = 0; i < NUM_RESOURCE_TEXTURE; i ++)
	{
		int chanel;
		_texture_image_data = CSOIL::GetInstance()->SOIL_load_image(fileNames[i], &_texture_image_w[i], &_texture_image_h[i], &chanel, SOIL_LOAD_AUTO);

		if(_texture_image_data == 0)
			printf("\nload %s fail", fileNames[i]);
		else
		{
			_textures[i] = CreateTextureImage(i, _texture_image_data, 
				_texture_image_w[i], _texture_image_h[i], 0, chanel);
			CSOIL::GetInstance()->SOIL_free_image_data(_texture_image_data);
			printf("\nload %s successful texture id = %d", fileNames[i], _textures[i]);
		}
	}
}

GLuint CSprite::CreateTextureImage(INT32 tex_id, UINT8* argb, INT32 w, INT32 h, bool linear_texture, INT8 palette)
{
	UINT32 texname;

	GLint color_type = GL_RGB;

	if(palette == SOIL_LOAD_RGBA)
		color_type = GL_RGBA;
	
	glEnable(GL_TEXTURE_2D);
	glGenTextures(1, &texname);
	glBindTexture(GL_TEXTURE_2D, texname);
	glTexImage2D(GL_TEXTURE_2D, 0, color_type, w, h, 0, color_type,
              GL_UNSIGNED_BYTE, argb);

	::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);//GL_NEAREST
	::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);//GL_NEAREST
	::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

	return texname;
}
	
void CSprite::Unload()
{	
	SAFE_DEL_ARRAY(_texture_image_w);
	SAFE_DEL_ARRAY(_texture_image_h)
}

void CSprite::DrawTexture(GLESLib* g, int texType, float x, float y, INT32 transform, INT32 opacity, INT8 palette)
{
	_uv[0] = 0.0f;
	_uv[1] = 0.0f;
	_uv[2] = 1.0f;
	_uv[3] = 1.0f;
	//printf("\n Draw2DTexture texType = %d, x = %f, y = %f", texType, x, y);
	g->Draw2DTexture(x, y, _texture_image_w[texType], _texture_image_h[texType], _textures[texType], _uv, DRAWTRIANGLE_FLAG, 1);
}
	